﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using My.Common.Helper.JqGrid;
using NCLCustomerManagement.BusinessLogic.Category;
using NCLCustomerManagement.BusinessLogic.Products;
using NCLCustomerManagement.BusinessLogic.Sale;
using NCLCustomerManagement.DataTransferObjects.Sale;
using NCLCustomerManagement.UI.Helper;
using NCLCustomerManagement.UI.Models;

namespace NCLCustomerManagement.UI.Controllers
{
    public class SaleController : BaseController
    {
        private IBuildGridDataHelper<SaleModel> _buildGridDataHelper;
        private ISaleBC _bc;
        private ICustomerBC _customerBC;
        private IProductBC _productBC;

        public SaleController(IBCFactory bcFactory,
            IProductBC productBC,
            IBuildGridDataHelper<SaleModel> gridHelper)
        {
            _bc = bcFactory.GetBC<ISaleBC>();
            _customerBC = bcFactory.GetBC<ICustomerBC>();
            _productBC = productBC;
            _buildGridDataHelper = gridHelper;
        }

        [AuthenticationRequired]
        public ActionResult Index()
        {
            PrepareProductSelectList();
            return View();
        }

        [AuthenticationRequired]
        public string GetSaleListForBuildingGrid(

            string customerPhone,
            string sortName = "Name",
            string sortOrder = "asc",
            int rowId = -1,
            int productId = -1,
            int categoryId = -1,
             DateTime? fromDate = null,
            DateTime? toDate = null
            )
        {
            if (fromDate == null)
                fromDate = DateTime.Now;
            if (toDate == null)
                toDate = DateTime.Now;
            var list = _bc.GetSaleList(fromDate.Value, toDate.Value, customerPhone,
                productId == -1 ? (int?)null : productId, categoryId == -1 ? (int?)null : categoryId)
                .Select(e => ConvertSale(e))
                .ToList();

            if (list.Count > 0)
            {
                var totalValue = list.Sum(e => e.TotalValue);
                Session["TotalSaleValue"] = totalValue;
            }
            else
            {
                Session["TotalSaleValue"] = 0;
            }

            if (list.Count > 0)
            {

                var totalUsedDays = list.Sum(e => e.AvailableDayUsed);
                var sortedList = list.OrderBy(e => e.SaleDate).ToList();
                var firstItem = sortedList.FirstOrDefault();
                if (firstItem != null)
                {
                    Session["EstimateExpiredDate"] = firstItem.SaleDate.AddDays(totalUsedDays);
                }
                else
                {
                    Session["EstimateExpiredDate"] = DateTime.Now;
                }
            }
            else
            {
                Session["EstimateExpiredDate"] = DateTime.Now;
            }
            return _buildGridDataHelper.BuildDataForGrid(list, this.CreateSaleListJson, sortName, sortOrder, rowId);
        }

        [AuthenticationRequired]
        public ActionResult GetSummaryInfo()
        {
            var date = Convert.ToDateTime(Session["EstimateExpiredDate"]);
            var saleValue = string.Format("{0:#,##0.00}", Session["TotalSaleValue"]);
            return Json(new
            {
                TotalSaleValue = saleValue,
                EstimateExpiredDate = date.ToString("dd/MM/yyyy")
            },
            JsonRequestBehavior.AllowGet);
        }

        [AuthenticationRequired]
        [HttpGet]
        public ActionResult New()
        {
            //PrepareCustomerSelectList();
            return View(new SaleModel());
        }

        [AuthenticationRequired]
        [HttpPost]
        public ActionResult New(SaleModel model)
        {

            var errList = ValidateSaleModel(model);
            if (model.CustomerId != 0)
            {
                model.CustomerName = _customerBC.GetCustomerById(model.CustomerId).CustomerName;
            }

            if (model.ProductId != 0)
            {
                var product = _productBC.GetProduct(model.ProductId);
                model.ProductName = product.ProductName;
                model.Unit = product.PrimaryUnit;
            }

            if (errList.Count() > 0)
            {
                foreach (var item in errList)
                    ModelState.AddModelError("", item);
                return View("New", model);
            }

            model.Id = Guid.NewGuid();
            model.SaleDate = DateTime.Now;
            model.CreatedBy = this.GetCurrentUser().Username;

            var dto = ConvertSale(model);

            try
            {
                _bc.AddNewSaleItem(dto);
                HistoryBC.AddHistory(new DataTransferObjects.History.HistoryDTO()
                {
                    Id = Guid.NewGuid(),
                    OperationDate = DateTime.Now,
                    Operation = string.Format("Ngày {3}: Bán {2} sản phẩm {0} cho khách hàng {1}",
                    dto.ProductName, dto.CustomerName, dto.Quantity,
                    dto.SaleDate.ToString("dd/MM/yyyy")),
                    Type = DataTransferObjects.History.HistoryType.Other,
                    Username = this.GetCurrentUser().Username
                });
                dto = null;
                model = new SaleModel();
                return RedirectToAction("Index");
            }
            catch (Exception)
            {
                ModelState.AddModelError("", "Không thể thêm");
                return View("New", model);
            }

        }

        private IEnumerable<string> ValidateSaleModel(SaleModel model)
        {
            if (model.CustomerId == 0)
            {
                yield return "Bạn chưa chọn khách hàng";
            }
            if (model.ProductId == 0)
            {
                yield return "Bạn chưa chọn sản phẩm";
            }
        }
        [HttpGet]
        [AuthenticationRequired]
        public ActionResult RenderSelectProductView()
        {
            return PartialView("_SelectProductPartial");
        }

        [AuthenticationRequired]
        public ActionResult Delete(string[] deletedIds)
        {
            var ok = true;
            var msg = "";
            try
            {
                //_bc.DeleteSaleItem(deletedIds.Select(e => Guid.Parse(e)).ToArray());
                foreach (var item in deletedIds)
                {
                    Delete(Guid.Parse(item));
                }
                ok = true;
                msg = "Đã xóa thành công";
            }
            catch (Exception)
            {
                ok = false;
                msg = "Đã xảy ra lỗi khi xóa. Bạn hãy thử lại sau";
            }
            return Json(new { Success = ok, Message = msg }, JsonRequestBehavior.AllowGet);
        }

        private void Delete(Guid id)
        {
            SaleDTO dto = _bc.GetSaleItem(id);
            _bc.DeleteSaleItem(id);

            HistoryBC.AddHistory(new DataTransferObjects.History.HistoryDTO()
            {
                Id = Guid.NewGuid(),
                OperationDate = DateTime.Now,
                Operation = string.Format("Xóa trong danh mục bán hàng: Ngày {3}: Bán {2} sản phẩm {0} cho khách hàng {1}",
                dto.ProductName, dto.CustomerName, dto.Quantity,
                dto.SaleDate.ToString("dd/MM/yyyy")),
                Type = DataTransferObjects.History.HistoryType.Other,
                Username = this.GetCurrentUser().Username
            });
        }
        private void PrepareCategorySelectList(int? selectedValue = null)
        {
            var cates = this.GetAllCategories(_customerBC).ToList();
            var cateSelectList = new SelectList(cates, "Id", "ProductCategoryName", selectedValue);
            ViewBag.CategorySelectList = cateSelectList;
        }

        private void PrepareProductSelectList(int? selectedValue = null)
        {
            var cates = this.GetAllProducts(_productBC).ToList();
            var cateSelectList = new SelectList(cates, "Id", "ProductName", selectedValue);
            ViewBag.ProductSelectList = cateSelectList;
        }

        //private void PrepareCustomerSelectList()
        //{
        //    var list = this.GetAllCustomers(_customerBC).ToList();
        //    var selectList = new SelectList(list, "Id", "CustomerName");
        //    ViewBag.CustomerSelectList = selectList;

        //}
        private SaleModel ConvertSale(SaleDTO dto)
        {
            return new SaleModel()
            {
                Discount = dto.Discount,
                UnitPrice = dto.UnitPrice,
                Quantity = dto.Quantity,
                CustomerId = dto.CustomerId,
                CustomerName = dto.CustomerName,
                Id = dto.Id,
                ProductId = dto.ProductId,
                ProductName = dto.ProductName,
                SaleDate = dto.SaleDate,
                Tax = dto.Tax,
                Unit = dto.Unit,
                AvailableDayUsed = dto.AvailableDayUsed,
                CreatedBy = dto.CreatedBy,
                Notes = dto.Notes,
            };
        }
        private SaleDTO ConvertSale(SaleModel model)
        {
            return new SaleDTO()
            {
                Discount = model.Discount,
                UnitPrice = model.UnitPrice,
                Quantity = model.Quantity,
                CustomerId = model.CustomerId,
                CustomerName = model.CustomerName,
                Id = model.Id,
                ProductId = model.ProductId,
                ProductName = model.ProductName,
                SaleDate = model.SaleDate,
                Tax = model.Tax,
                Unit = model.Unit,
                AvailableDayUsed = model.AvailableDayUsed,
                CreatedBy = model.CreatedBy,
                Notes = model.Notes

            };
        }

    }
}
